import cv2
import numpy as np
def Division_Merge_Segmented(file_path,fmin,fmax):
    # 读取图片
    def Division_Judge(img, h0, w0, h, w):
        area = img[h0:h0 + h, w0:w0 + w]
        mean = np.mean(area)
        std = np.std(area, ddof=1)

        total_points = 0
        operated_points = 0

        for row in range(area.shape[0]):
            for col in range(area.shape[1]):
                if (area[row][col] - mean) < 2 * std:
                    operated_points += 1
                total_points += 1

        if operated_points / total_points >= 0.95:
            return True
        else:
            return False

    def Recursion(img, h0, w0, h, w, fmin1, fmax1):
        if not Division_Judge(img, h0, w0, h, w) and min(h, w) > 5:
            Recursion(img, h0, w0, int(h / 2), int(w / 2))
            Recursion(img, h0, w0 + int(w / 2), int(h / 2), int(w / 2))
            Recursion(img, h0 + int(h / 2), w0, int(h / 2), int(w / 2))
            Recursion(img, h0 + int(h / 2), w0 +int(w / 2), int(h / 2), int(w / 2))
        else:
            for row in range(h0, h0 + h):
                for col in range(w0, w0 + w):
                    if img[row, col] > fmin1 and img[row, col] < fmax1:
                        img[row, col] = 0
                    else:
                        img[row, col] = 255
    img = cv2.imread(file_path, cv2.IMREAD_GRAYSCALE)
    # 分割图片

    Recursion(img, 0, 0, img.shape[0], img.shape[1], int(fmin), int(fmax))

    # 删除空白区域
    img = img[1:-1, 1:-1]  # 删除边缘

    # 保存分割后的图片
    return img

def region_growing(x,y,n,img_path):
    recent_Point = (x, y)

    def region_grow(src, pt, th):
        mat_dst = np.zeros_like(src, dtype=np.uint8)  # 创建一个空白区域，填充为黑色
        DIR = [(-1, -1), (0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0)]  # 生长方向
        grow_stack = [pt]  # 使用列表作为栈
        mat_dst[pt[1], pt[0]] = 255  # 标记生长点
        src_value = src[pt[1], pt[0]]  # 记录生长点的灰度值

        while grow_stack:  # 生长栈不为空则生长
            pt = grow_stack.pop()

            # 遍历八个方向
            for dx, dy in DIR:
                pt_growing = (pt[0] + dx, pt[1] + dy)

                # 检查是否越界
                if 0 <= pt_growing[0] < src.shape[1] and 0 <= pt_growing[1] < src.shape[0]:
                    grow_label = mat_dst[pt_growing[1], pt_growing[0]]  # 当前待生长点的灰度值
                    if grow_label == 0:  # 如果标记点还没有被生长
                        cur_value = src[pt_growing[1], pt_growing[0]]
                        # print(abs(src_value - cur_value))
                        if abs(int(src_value) - int(cur_value)) < th:  # 在阈值范围内则生长
                            mat_dst[pt_growing[1], pt_growing[0]] = 255  # 标记为白色
                            grow_stack.append(pt_growing)  # 将下一个生长点压入栈中

        return mat_dst
    threshold_value = int(n)
    src = cv2.imread(img_path)
    if src is None:
        print("Error: Unable to load image.")
        return
    gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
    _, binary = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY)

    temp_regiongrow = np.zeros_like(binary, dtype=np.uint8)  # 累积生长区域的图像
    if recent_Point is not None:
        regiongrow1 = region_grow(binary, recent_Point, threshold_value)
        temp_regiongrow = cv2.bitwise_or(temp_regiongrow, regiongrow1)  # 累积生长区域
        gray_segmented = cv2.bitwise_and(gray, temp_regiongrow.astype(np.uint8), mask=temp_regiongrow)
    return gray_segmented